package com.mall.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.common.result.Result;
import com.mall.system.entity.Config;
import com.mall.system.service.ConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 系统配置控制器
 */
@Tag(name = "系统配置管理")
@Slf4j
@RestController
@RequestMapping("/system/configs")
public class ConfigController {
    
    @Autowired
    private ConfigService configService;
    
    @Operation(summary = "系统配置列表")
    @GetMapping
    public Result<IPage<Config>> list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            Config config) {
        try {
            IPage<Config> page = new Page<>(pageNum, pageSize);
            QueryWrapper<Config> queryWrapper = new QueryWrapper<>();
            
            // 添加查询条件
            if (config.getConfigName() != null && !config.getConfigName().isEmpty()) {
                queryWrapper.like("config_name", config.getConfigName());
            }
            if (config.getConfigKey() != null && !config.getConfigKey().isEmpty()) {
                queryWrapper.like("config_key", config.getConfigKey());
            }
            
            queryWrapper.orderByDesc("create_time");
            
            IPage<Config> result = configService.page(page, queryWrapper);
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询系统配置列表异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "根据系统配置ID获取系统配置")
    @GetMapping("/{configId}")
    public Result<Config> getById(@PathVariable("configId") Long configId) {
        try {
            Config config = configService.getById(configId);
            if (config != null) {
                return Result.success(config);
            } else {
                return Result.failed("系统配置不存在");
            }
        } catch (Exception e) {
            log.error("查询系统配置异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "根据参数键名获取参数值")
    @GetMapping("/key/{configKey}")
    public Result<String> getConfigValueByKey(@PathVariable("configKey") String configKey) {
        try {
            String configValue = configService.selectConfigByKey(configKey);
            if (configValue != null) {
                return Result.success(configValue);
            } else {
                return Result.failed("系统配置不存在");
            }
        } catch (Exception e) {
            log.error("根据参数键名获取参数值异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "新增系统配置")
    @PostMapping
    public Result<Boolean> add(@RequestBody Config config) {
        try {
            // 检查参数键名是否已存在
            QueryWrapper<Config> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("config_key", config.getConfigKey());
            if (configService.getOne(queryWrapper) != null) {
                return Result.failed("参数键名已存在");
            }
            
            boolean success = configService.save(config);
            if (success) {
                return Result.success(true);
            } else {
                return Result.failed("新增系统配置失败");
            }
        } catch (Exception e) {
            log.error("新增系统配置异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "更新系统配置")
    @PutMapping
    public Result<Boolean> update(@RequestBody Config config) {
        try {
            if (config.getConfigId() == null) {
                return Result.failed("系统配置ID不能为空");
            }
            
            boolean success = configService.updateById(config);
            if (success) {
                return Result.success(true);
            } else {
                return Result.failed("更新系统配置失败");
            }
        } catch (Exception e) {
            log.error("更新系统配置异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "删除系统配置")
    @DeleteMapping("/{ids}")
    public Result<Boolean> delete(@PathVariable("ids") List<Long> ids) {
        try {
            // 检查是否包含系统内置配置
            QueryWrapper<Config> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("config_id", ids);
            queryWrapper.eq("config_type", "Y");
            if (configService.getOne(queryWrapper) != null) {
                return Result.failed("不能删除系统内置配置");
            }
            
            boolean success = configService.removeByIds(ids);
            if (success) {
                return Result.success(true);
            } else {
                return Result.failed("删除系统配置失败");
            }
        } catch (Exception e) {
            log.error("删除系统配置异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
}